package com.example.demo.service.impl;

import com.example.demo.entity.Category;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.CategoryMapper;
import com.example.demo.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 分类服务实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    
    private static final Logger log = LoggerFactory.getLogger(CategoryServiceImpl.class);
    
    private final CategoryMapper categoryMapper;
    
    public CategoryServiceImpl(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }
    
    @Override
    public Category getCategoryById(Long id) {
        return categoryMapper.selectById(id);
    }
    
    @Override
    public Category getCategoryByName(String name) {
        return categoryMapper.selectByName(name);
    }
    
    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.selectAllCategories();
    }
    
    @Override
    public List<Category> getCategoriesWithArticles() {
        return categoryMapper.selectCategoriesWithArticles();
    }
    
    @Override
    public Category createCategory(Category category) {
        if (!StringUtils.hasText(category.getName())) {
            throw new BusinessException("分类名称不能为空");
        }
        
        LocalDateTime now = LocalDateTime.now();
        category.setCreateTime(now);
        category.setUpdateTime(now);
        category.setArticleCount(0);
        
        int rows = categoryMapper.insert(category);
        if (rows != 1) {
            throw new BusinessException("创建分类失败");
        }
        
        return category;
    }
    
    @Override
    public Category updateCategory(Category category) {
        if (category.getId() == null) {
            throw new BusinessException("分类ID不能为空");
        }
        
        int rows = categoryMapper.update(category);
        if (rows != 1) {
            throw new BusinessException("更新分类失败");
        }
        
        return categoryMapper.selectById(category.getId());
    }
    
    @Override
    public boolean deleteCategory(Long id) {
        return categoryMapper.deleteById(id) == 1;
    }
    
    @Override
    public void updateArticleCount(Long categoryId) {
        // 这里应该统计该分类下的文章数量，简化处理
        categoryMapper.updateArticleCount(categoryId, 0);
    }
    
    @Override
    public long getTotalCategoryCount() {
        return categoryMapper.selectTotalCount();
    }
}
